package com.itic.mall.mobile.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.utils.CalendarHelper;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.marketuserproduct.persistence.model.MarketUserProduct;
import com.itic.mall.system.marketuserproduct.service.MarketUserProductService;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.persistence.model.OrderExample;
import com.itic.mall.system.order.persistence.model.OrderExample.Criteria;
import com.itic.mall.system.order.persistence.model.OrderVo;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderexpress.persistence.model.OrderExpress;
import com.itic.mall.system.orderjd.persistence.model.OrderJd;
import com.itic.mall.system.orderjd.persistence.model.OrderJdExample;
import com.itic.mall.system.orderjd.service.OrderJdService;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProducts;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsExample;
import com.itic.mall.system.orderjdproducts.service.OrderJdProductsService;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsFeedbackVo;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsParam;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsVo;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.paymoney.persistence.model.PayMoney;
import com.itic.mall.system.premoney.persistence.model.PreMoney;
import com.itic.mall.system.premoney.persistence.model.PreMoneyExample;
import com.itic.mall.system.premoney.service.PreMoneyService;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.persistence.model.ProductOrderVo;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.productfeedback.persistence.model.ProductFeedback;
import com.itic.mall.system.productfeedback.service.ProductFeedbackService;
import com.itic.mall.system.productsku.persistence.model.ProductSku;
import com.itic.mall.system.productsku.service.ProductSkuService;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoney;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.itic.mall.system.useraddress.persistence.model.UserAddress;
import com.itic.mall.system.useraddress.persistence.model.UserAddressExample;
import com.itic.mall.system.useraddress.service.UserAddressService;


/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/order")
public class MallOrderInterface
     extends BaseMobileInterface {
   @Autowired
   private ProductService productService;
   @Autowired
   private ProductSkuService productSkuService;
   @Autowired
   private ProductFeedbackService productFeedbackService;
   @Autowired
   private OrderService orderService;
   @Autowired
   private OrderJdService orderJdService;
   @Autowired
   private OrderJdProductsService orderJdProductsService;
   @Autowired
   private OrderProductsService orderProductsService;
   @Autowired
   private MarketUserService marketUserService;
   @Autowired
   private MarketUserProductService marketUserProductService;
   @Autowired
   private UserAddressService userAddressService;
   @Autowired
   private PreMoneyService preMoneyService;
   
   private static final String ORDER_ID = "orderId";
   private static final String TOTAL_MONEY = "totalMoney";
   
   
   /**
    * 根据订单ID获取订单信息
    * @param request
    * @param response
    * @param token
    * @return
    */
   @RequestMapping(value="/isOneOrder")
   @ResponseBody
   public Map<String,Object> isOneOrder( HttpServletRequest request,HttpServletResponse response,String token ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		if( StringHelper.isNotBlank(token)){
	   			MallUser user = getMallUserByToken(token);
	   			OrderExample example = new OrderExample();
		   		Criteria criteria = example.createCriteria();
		   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   		criteria.andUserIdEqualTo(user.getId());
		   		criteria.andPayTimeIsNotNull();
		   		List<Order> list = orderService.list(example);
		        if( list.size()>0 ){
		        	resultMap.put(DATA, "no");
		        }else{
		        	resultMap.put(DATA, "yes");
		        }
		   		result = SUCCESS;
			    errorCode = SUCCESS_ERROR_CODE;
			 	errorMsg = SUCCESS_ERROR_MSG; 
	   		}
	   		
	   	    
	   	}catch( Exception e ){
	   		errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "jdOrders", e.toString(),"查看京东业绩信息",e);
  		
	   	}
	   	resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   
   /**
    * 根据订单ID获取订单信息
    * @param request
    * @param response
    * @param token
    * @return
    */
   @RequestMapping(value="/jdOrderProducts")
   @ResponseBody
   public Map<String,Object> jdOrderProducts( HttpServletRequest request,HttpServletResponse response,String id ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		
	   		if( StringHelper.isNotBlank(id)){
	   			OrderJdProductsExample example = new OrderJdProductsExample();
		   		com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsExample.Criteria criteria = example.createCriteria();
		   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   		criteria.andOrderIdEqualTo(id);
		   		
		   		List<OrderJdProducts> list = orderJdProductsService.list(example);
		   		resultMap.put(DATA, list);
		   		result = SUCCESS;
			    errorCode = SUCCESS_ERROR_CODE;
			 	errorMsg = SUCCESS_ERROR_MSG; 
	   		}
	   		
	   	    
	   	}catch( Exception e ){
	   		errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "jdOrders", e.toString(),"查看京东业绩信息",e);
  		
	   	}
	   	resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   /**
    * 根据订单ID获取订单信息
    * @param request
    * @param response
    * @param token
    * @return
    */
   @RequestMapping(value="/jdOrders")
   @ResponseBody
   public Map<String,Object> jdOrders( HttpServletRequest request,HttpServletResponse response, String orderNum, String tgwName, String startTime, String endTime ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		
	   		Map<String, Object> dataMap = new HashMap<String,Object>();
	   	 
	   		OrderJdExample example = new OrderJdExample();
	   		example.setOrderByClause("ORDER_DATE DESC");
	   		
	   		com.itic.mall.system.orderjd.persistence.model.OrderJdExample.Criteria criteria = example.createCriteria();
	   		
	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   	
	   		if( StringHelper.isNotBlank(tgwName) ){
	   			criteria.andTgwNameLike("%"+tgwName+"%");
	   		}
	   		
	   		if( StringHelper.isNotBlank(orderNum) ){
	   			criteria.andOrderNumLike("%"+orderNum+"%");
	   		}
	   		
	   		if( StringHelper.isNotBlank(startTime) ){
	   			
	   			criteria.andOrderDateGreaterThanOrEqualTo(DateHelper.getDateByStringDateYYYYMMDD(startTime+IticConst.START_TIME_SUFFIX));
	   		}
	   		
	   		if( StringHelper.isNotBlank(endTime) ){
	   			criteria.andOrderDateLessThanOrEqualTo(DateHelper.getDateByStringDateYYYYMMDD(endTime+IticConst.END_TIME_SUFFIX));
	   		}
	   		
	   		this.handlePageQueryDefault(request, example);
	   		int count = orderJdService.count(example);
	   		List<OrderJd> list = orderJdService.list(example);
	   		
	   		dataMap.put("count", count);
	   		dataMap.put("orders", list);
	   		
	   		resultMap.put(DATA, dataMap);
	   		result = SUCCESS;
		    errorCode = SUCCESS_ERROR_CODE;
		 	errorMsg = SUCCESS_ERROR_MSG; 
	   	    
	   	}catch( Exception e ){
	   		errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "jdOrders", e.toString(),"查看京东业绩信息",e);
  		
	   	}
	   	resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   /**
    * 根据订单ID获取订单信息
    * @param request
    * @param response
    * @param token
    * @return
    */
   @RequestMapping(value="/get")
   @ResponseBody
   public Map<String,Object> get( HttpServletRequest request,HttpServletResponse response,String id ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   	    //判断必要的参数
	   		if( StringHelper.isNotBlank(id) ){
	   			Order order = orderService.get(id);
	   			if( null != order ){
	   				MallUser mallUser = mallUserService.get(order.getUserId());
	   				GzhOrder gzhOrder = new GzhOrder();
	   				gzhOrder.setOrderId(id);
	   				gzhOrder.setTotalMoney(order.getTotalMoney());
	   				gzhOrder.setOpenid(mallUser.getOpenid());
	   				resultMap.put(DATA, gzhOrder);
	   				
	   				result = SUCCESS;
	   			    errorCode = SUCCESS_ERROR_CODE;
	   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   			}else{
	   				result = FAIL;
	   			    errorCode = ORDER_NULL_ERROR_CODE;
	   			 	errorMsg = ORDER_NULL_ERROR_MSG; 
	   			}
	   		}
	   	}catch( Exception e ){
	   		errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "get", e.toString(),"根据订单ID获取订单信息",e);
   		
	   	}
	   	resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   /**
    * 添加地址的时候是否是第一个地址？ 如果是返回1，如果不是返回0
    * @param request
    * @param response
    * @param token
    * @return
    */
   @RequestMapping(value="/isOneAddress")
   @ResponseBody
   public Map<String,Object> isOneAddress( HttpServletRequest request,HttpServletResponse response,String token ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   	    //判断必要的参数
	   		if( StringHelper.isNotBlank(token) ){
	   			String isOne = "1";
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				UserAddressExample example = new UserAddressExample();
	   				com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria criteria = example.createCriteria();
	   				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   				criteria.andUserIdEqualTo(user.getId());
	   				List<UserAddress> list = userAddressService.list(example);
	   				if( list.size() > 0 ){
	   					isOne = "0";
	   				}
	   				resultMap.put(DATA, isOne);
	   				result = SUCCESS;
	   			    errorCode = SUCCESS_ERROR_CODE;
	   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   			}else{
	   				result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  
	   			}
	   		}
	   	}catch( Exception e ){
	   		errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "isOneAddress", e.toString(),"判断是否有一个地址方法",e);
    		
	   	}
	   	resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   
   /**
    * 购物车预创建订单
    * @param request
    * @param response
    * @param token
    * @param products
    * @return
    */
   @RequestMapping(value="/preCreateSeckill")
   @ResponseBody
   public Map<String,Object> preCreateSeckill(  HttpServletRequest request,HttpServletResponse response,String token, String products, String marketUserProductId ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) ){
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				String isHaveAddress = "0"; 
	   			    UserAddress mainAddress = null;
	   			    List<ProductOrderVo> productsDetail = new ArrayList<ProductOrderVo>();
	   			    String totalHongbao="0";//总优惠红包金额
	   			    String totalOriginPrice = "0";//商品总价格
	   			    String totalPostFee = "0";//商品总邮费
	   			    String totalPrice = "0";//商品总价
	   			    
	   				//查找用户有没有收货地址
	   				UserAddressExample example = new UserAddressExample();
	   				com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria criteria = example.createCriteria();
	   				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   				criteria.andUserIdEqualTo(user.getId());
	   				criteria.andIsMainEqualTo(DBConst.TRUE);
	   				List<UserAddress> list = userAddressService.list(example);
	   				if( list.size() > 0 ){
	   					isHaveAddress = "1";
	   					mainAddress = list.get(0);
	   				}
	   				
	   				String[] productsStr = products.split(",");
	   				
	   				if( productsStr.length > 0 ){
	   					for( int i=0; i<productsStr.length; i++ ){
	   						String[] temp = productsStr[i].split(":");
	   						String productId = "";
	   						String productSkuId = "";
	   						if( null != temp ){
	   							productId = temp[0];//商品ID
	   							productSkuId = temp[1];
	   						}
    						
    						Product product = productService.get(productId);
    						//product.setProductPrice(getProductPriceString(user.getId(),));
    						//product = filterPriceByUser(user, product);
    						product.setProductPrice(product.getSeckillPrice());
    						
    						ProductSku productSku = productSkuService.get(productSkuId);
    						
    						//productSku = filterSkuPriceByUser(user, productSku);
    						//productSku = filterSkuPriceByUser(user,productSku);
    						productSku.setProductPrice(product.getSeckillPrice());
    						
    						if( null != product ){
    							ProductOrderVo vo = new ProductOrderVo();
    							//String haveHongbao = isHaveHongbao(user.getId(), product.getId());
    							//判断红包是否在有效期内
    							//String hongbao = getHongbaoOrder(product);
    							
    							vo.setTotalCount(temp[2]);
    							vo.setName(product.getName());
    							vo.setMainImageUrl(product.getMainImageUrl());
    							vo.setTotalFeedback(product.getTotalFeedback());
    							if( StringHelper.isNotBlank(product.getPercentFeedback()) ){
    								double parseDouble = Double.parseDouble(product.getPercentFeedback());
    								int value = (int)parseDouble;
    								product.setPercentFeedback(value+"");
    							}
    							vo.setPercentFeedback(product.getPercentFeedback()==""?"100":product.getPercentFeedback());
    							//vo.setProductPrice(productSku.getProductPrice());
    							
    							vo.setProductOrginPrice(productSku.getProductOrginPrice());
    							//vo.setProductHongbao(productSku.getProductHongbao());
    							vo.setIsServenBack(product.getIsServenBack());
    							vo.setIsFreePost(product.getIsFreePost());
    							
    							vo.setProductPrice(productSku.getProductPrice());
    							//String totalHongbaoTemp = NumberStringHelper.mulString(temp[2], productSku.getProductHongbao());
    							//totalHongbao = NumberStringHelper.addString(totalHongbao, totalHongbaoTemp);
    							
    							String totalPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductPrice());
    							totalPrice = NumberStringHelper.addString(totalPrice, totalPriceTemp);
    							
    							String totalOriginPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
    							totalOriginPrice = NumberStringHelper.addString(totalOriginPrice, totalOriginPriceTemp);
    							
    							productsDetail.add(vo);
    							
    						}
	   					}
	   					
	   					Map<String, Object> dataMap = new HashMap<String,Object>(); 
		   			    dataMap.put("products", productsDetail);
		   			    dataMap.put("mainAddress", mainAddress);
		   			    dataMap.put("paramProducts", products);
		   			    dataMap.put("paramMarketUserProductId", marketUserProductId);
		   			    dataMap.put("isHaveAddress", isHaveAddress);
		   			    
		   			    dataMap.put("totalHongbao", totalHongbao);
		   			    dataMap.put("totalOriginPrice", totalOriginPrice);
		   			    dataMap.put("totalPostFee", totalPostFee);
		   			    dataMap.put("totalPrice", totalPrice);
		   			    resultMap.put(DATA, dataMap);
		   			    result = SUCCESS;
		   			    errorCode = SUCCESS_ERROR_CODE;
		   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   				}else{
    					result = FAIL;
            			errorCode = PRODUCT_EMPTY_ERROR_CODE;
                    	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
    				}
	   			    
	   			}else{
					result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  	
				}
			}
	   		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "preCreateSeckill", e.toString(),"预产生订单",e);
    		
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   /**
    * 
    * @param request
    * @param response
    * @param token
    * @param note
    * @param addressId
    * @param products
    * @param marketUserProductId
    * @param type
    * @return
    */
   public Map<String,Object> createNew( HttpServletRequest request,HttpServletResponse response,String token, String note,String addressId, String products,String marketUserProductId, String type ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) && StringHelper.isNotBlank(addressId) ){
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				if( isOneOrder(user.getId()) ){
		   				Map<String, Object> dataMap = new HashMap<String,Object>();
		   				//解析 产品ID 和数量
		   				String[] productsStr = products.split(",");
		   				if( productsStr.length > 0 ){
		   					List<OrderProducts> orderProducts = new ArrayList<OrderProducts>();
		   					Date date = new Date();
		   					//过期时间30分钟
		   					Date dateAfter30 = CalendarHelper.getMinuteAfter(date, 30);
		   					String date30 = DateHelper.formatDateTime(dateAfter30);
		   					String orderId = IdGen.uuid();
		   					String userId = user.getId();
		   					String totalProduct = "0";
		   					String totalMoney = "0";
		   					//String isHaveMarket = "0";//订单是否有商家ID
		   					String marketUserId = "";
		   					String orderNum = RandomOrderNumHelper.getOrderNumber();
		   					if( StringHelper.isNotBlank(marketUserProductId) ){
		   						
		   						MarketUserProduct userProduct = marketUserProductService.get(marketUserProductId);
		   						if( null != userProduct ){
		   							MarketUser user2 = marketUserService.get(userProduct.getUserId());
		   							if( null != user2 ){
		   								marketUserId = user2.getId();
		   							}
		   						}
		   						//isHaveMarket = "1";
		   					}
		   					
		   					for( int i=0; i<productsStr.length; i++ ){
		   						String[] temp = productsStr[i].split(":");
		   						if( temp.length > 2 ){
		   							
		   							String productId = temp[0];//商品ID
		       						String productSkuId = temp[1];//商品的SKUID
		       						String productCount = temp[2];//商品数量
		       						
		       						Product product = productService.get(productId);
		       						ProductSku productSku = productSkuService.get(productSkuId);
		       						
		       						if( StringHelper.isNotBlank(type) ){
		       							productSku.setProductPrice(product.getSeckillPrice());
		       						}else{
		       							productSku = filterSkuPriceByUser(user, productSku);
		       						}
		       						
		       						
		       						String tempTotalMoney = NumberStringHelper.mulString(productSku.getProductPrice(), productCount);
		       						//String tempTotalProduct = NumberStringHelper.addString(productCount, totalProduct);
		       						totalMoney = NumberStringHelper.addString(tempTotalMoney, totalMoney);
		       						totalProduct = NumberStringHelper.addString(productCount, totalProduct);
		       						
		       						OrderProducts orderProduct = new OrderProducts();
		       						//6个必填项
		       						orderProduct.setId(IdGen.uuid());
		       						orderProduct.setIsEffective(DBConst.TRUE);
		       						orderProduct.setOrgCode(ORG_CODE);
		       						orderProduct.setCreateUser(CREATE_USER);
		       						orderProduct.setCreateTime(date);
		       						orderProduct.setUpdateTime(date);
		       						//关联字段
		       						orderProduct.setOrderId(orderId);
		       						orderProduct.setProductId(productId);
		       						orderProduct.setPropertySkuId(productSkuId);
		       						orderProduct.setMarketUserProductId(marketUserProductId);//商品推广ID
		       						orderProduct.setMarketUserId(marketUserId);
		       						orderProduct.setUserId(userId);//用户字段
		       						orderProduct.setStatus("0");//订单状态为未支付状态
		       						orderProduct.setBackStatus("0");//退换货状态不生效
		       						//填充字段
		       						orderProduct.setIsFeedback("0");//未评价状态
		       						//业务字段 
		       						orderProduct.setTotalCount(productCount);//商品数量
		       						orderProduct.setTotalMoney("1");//商品总金额
		       						
		       						orderProducts.add(orderProduct);
		   						}
		   					}
		   					
		   					Order order = new Order();
		   					//6个必填字段
		   					order.setId(orderId);
		   					order.setIsEffective(DBConst.TRUE);
		   					order.setOrgCode(ORG_CODE);
		   					order.setCreateUser(CREATE_USER);
		   					order.setCreateTime(date);
		   					order.setUpdateTime(date);
		   					
		   					//关联字段
		   					order.setUserId(userId);
		   					order.setUserAddressId(addressId);
		   					//默认填充字段
		   					order.setStatus("0");//订单状态
		   					//order.setIsHaveMarket(isHaveMarket);
		   					//order.setOrderIsConfirm("0");//订单未确认收货
		   					order.setOrderIsExpired("0");//订单未过期
		   					//order.setOrderIsFeedback("0");//订单未评价
		   					//order.setOrderIsPay("0");//订单未支付 
		   					//业务字段
		   					order.setOrderNum(orderNum);//订单号码
		   					order.setTotalMoney("1");
		   					order.setTotalProduct(totalProduct);
		   					order.setOrderExpiredTime(date30);
		   					order.setNote(note);
		   					
		   					//更新数据库
		   					result = orderService.createOrder(order,orderProducts);
		   					//清空购物车
		   					
		   					
		           			errorCode = SUCCESS_ERROR_CODE;
		                   	errorMsg = SUCCESS_ERROR_MSG; 
		                   	
		                   	dataMap.put(ORDER_ID, orderId);
		                   	dataMap.put(TOTAL_MONEY, "1");
		                   	resultMap.put(DATA, dataMap);
		   					
		   				}else{
		   					result = FAIL;
		           			errorCode = PRODUCT_EMPTY_ERROR_CODE;
		                   	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
		   				}
		   				
		   			
	   				}else{
	   					result = FAIL;
		       			errorCode = NOT_ONE_ORDER_ERROR_CODE;
		               	errorMsg = NOT_ONE_ORDER_ERROR_MSG;  
	   				}
	   			}else{
	   				result = LOGIN;
	       			errorCode = LOGIN_ERROR_CODE;
	               	errorMsg = LOGIN_ERROR_MSG;  	
	   			}
	   		}
	   	}catch(Exception e){
	   		errorCode = SERVER_ERROR_CODE;
	       	errorMsg = SERVER_ERROR_MSG;
	       	//log(e);
	       	logException("MallOrderInterface", "createNew", e.toString(),"新手生成订单",e);
	   		
	   	}
	   	resultMap.put(RESULT, result);
	   	resultMap.put(ERROR_CODE, errorCode);
	   	resultMap.put(ERROR_MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
   }
   
   /**
    * 购物车预创建订单
    * @param request
    * @param response
    * @param token
    * @param products
    * @return
    */
   @RequestMapping(value="/preCreateNew")
   @ResponseBody
   public Map<String,Object> preCreateNew(  HttpServletRequest request,HttpServletResponse response,String token, String products, String marketUserProductId ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) ){
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				if( isOneOrder(user.getId()) ){
	   					String isHaveAddress = "0"; 
		   			    UserAddress mainAddress = null;
		   			    List<ProductOrderVo> productsDetail = new ArrayList<ProductOrderVo>();
		   			    String totalHongbao="0";//总优惠红包金额
		   			    String totalOriginPrice = "0";//商品总价格
		   			    String totalPostFee = "0";//商品总邮费
		   			    String totalPrice = "0";//商品总价
		   			    
		   				//查找用户有没有收货地址
		   				UserAddressExample example = new UserAddressExample();
		   				com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria criteria = example.createCriteria();
		   				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		   				criteria.andUserIdEqualTo(user.getId());
		   				criteria.andIsMainEqualTo(DBConst.TRUE);
		   				List<UserAddress> list = userAddressService.list(example);
		   				if( list.size() > 0 ){
		   					isHaveAddress = "1";
		   					mainAddress = list.get(0);
		   				}
		   				
		   				String[] productsStr = products.split(",");
		   				
		   				if( productsStr.length > 0 ){
		   					for( int i=0; i<productsStr.length; i++ ){
		   						String[] temp = productsStr[i].split(":");
		   						String productId = "";
		   						String productSkuId = "";
		   						if( null != temp ){
		   							productId = temp[0];//商品ID
		   							productSkuId = temp[1];
		   						}
	    						
	    						Product product = productService.get(productId);
	    						//product.setProductPrice(getProductPriceString(user.getId(),));
	    						product = filterPriceByUser(user, product);
	    						ProductSku productSku = productSkuService.get(productSkuId);
	    						productSku = filterSkuPriceByUser(user, productSku);
	    						//productSku = filterSkuPriceByUser(user,productSku);
	    						
	    						if( null != product ){
	    							ProductOrderVo vo = new ProductOrderVo();
	    							String haveHongbao = isHaveHongbao(user.getId(), product.getId());
	    							//判断红包是否在有效期内
	    							String hongbao = getHongbaoOrder(product);
	    							
	    							vo.setTotalCount(temp[2]);
	    							vo.setName(product.getName());
	    							vo.setMainImageUrl(product.getMainImageUrl());
	    							vo.setTotalFeedback(product.getTotalFeedback());
	    							if( StringHelper.isNotBlank(product.getPercentFeedback()) ){
	    								double parseDouble = Double.parseDouble(product.getPercentFeedback());
	    								int value = (int)parseDouble;
	    								product.setPercentFeedback(value+"");
	    							}
	    							vo.setPercentFeedback(product.getPercentFeedback()==""?"100":product.getPercentFeedback());
	    							//vo.setProductPrice(productSku.getProductPrice());
	    							
	    							vo.setProductOrginPrice(productSku.getProductOrginPrice());
	    							//vo.setProductHongbao(productSku.getProductHongbao());
	    							vo.setIsServenBack(product.getIsServenBack());
	    							vo.setIsFreePost(product.getIsFreePost());
	    							
	    							if( "1".equals(haveHongbao) && NumberStringHelper.isGreaterNoEqual(hongbao, "0") ){
	    								vo.setProductPrice(productSku.getProductPrice());
	    								
	        							String totalHongbaoTemp = NumberStringHelper.mulString(temp[2], productSku.getProductHongbao());
	        							totalHongbao = NumberStringHelper.addString(totalHongbao, totalHongbaoTemp);
	        							
	        							String totalPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductPrice());
	        							totalPrice = NumberStringHelper.addString(totalPrice, totalPriceTemp);
	        							
	        							String totalOriginPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
	        							totalOriginPrice = NumberStringHelper.addString(totalOriginPrice, totalOriginPriceTemp);
	        							
	        							productsDetail.add(vo);
	        							
	    							}else{
	    								vo.setProductPrice(productSku.getProductOrginPrice());
	        							//String totalHongbaoTemp = NumberStringHelper.mulString(temp[2], productSku.getProductHongbao());
	        							//totalHongbao = NumberStringHelper.addString(totalHongbao, totalHongbaoTemp);
	        							
	        							String totalPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
	        							totalPrice = NumberStringHelper.addString(totalPrice, totalPriceTemp);
	        							
	        							String totalOriginPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
	        							totalOriginPrice = NumberStringHelper.addString(totalOriginPrice, totalOriginPriceTemp);
	        							
	        							productsDetail.add(vo);
	    							}
	    							
	    						}
		   					}
		   					
		   					Map<String, Object> dataMap = new HashMap<String,Object>(); 
			   			    dataMap.put("products", productsDetail);
			   			    dataMap.put("mainAddress", mainAddress);
			   			    dataMap.put("paramProducts", products);
			   			    dataMap.put("paramMarketUserProductId", marketUserProductId);
			   			    dataMap.put("isHaveAddress", isHaveAddress);
			   			    
			   			    dataMap.put("totalHongbao", totalHongbao);
			   			    dataMap.put("totalOriginPrice", totalOriginPrice);
			   			    dataMap.put("totalPostFee", totalPostFee);
			   			    dataMap.put("totalPrice", "1");
			   			    resultMap.put(DATA, dataMap);
			   			    
			   			    result = SUCCESS;
			   			    errorCode = SUCCESS_ERROR_CODE;
			   			 	errorMsg = SUCCESS_ERROR_MSG; 
		   				}else{
	    					result = FAIL;
	            			errorCode = NOT_ONE_ORDER_ERROR_CODE;
	                    	errorMsg = NOT_ONE_ORDER_ERROR_MSG; 
	    				}
	   				}else{
	   					result = FAIL;
            			errorCode = PRODUCT_EMPTY_ERROR_CODE;
                    	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
	   				}
	   			}else{
					result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  	
				}
			}
	   		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "preCreate", e.toString(),"预产生订单",e);
    		
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
   
   /**
    * 购物车预创建订单
    * @param request
    * @param response
    * @param token
    * @param products
    * @return
    */
   @RequestMapping(value="/preCreate")
   @ResponseBody
   public Map<String,Object> preCreate(  HttpServletRequest request,HttpServletResponse response,String token, String products, String marketUserProductId,String type ){
	    Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String result = FAIL;
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
	   	try{
	   		//判断必要的参数
	   		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) ){
	   			MallUser user = getMallUserByToken(token);
	   			if( null != user ){
	   				String isHaveAddress = "0"; 
	   			    UserAddress mainAddress = null;
	   			    List<ProductOrderVo> productsDetail = new ArrayList<ProductOrderVo>();
	   			    String totalHongbao="0";//总优惠红包金额
	   			    String totalOriginPrice = "0";//商品总价格
	   			    String totalPostFee = "0";//商品总邮费
	   			    String totalPrice = "0";//商品总价
	   			    
	   				//查找用户有没有收货地址
	   				UserAddressExample example = new UserAddressExample();
	   				com.itic.mall.system.useraddress.persistence.model.UserAddressExample.Criteria criteria = example.createCriteria();
	   				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	   				criteria.andUserIdEqualTo(user.getId());
	   				criteria.andIsMainEqualTo(DBConst.TRUE);
	   				List<UserAddress> list = userAddressService.list(example);
	   				if( list.size() > 0 ){
	   					isHaveAddress = "1";
	   					mainAddress = list.get(0);
	   				}
	   				
	   				String[] productsStr = products.split(",");
	   				
	   				if( productsStr.length > 0 ){
	   					for( int i=0; i<productsStr.length; i++ ){
	   						String[] temp = productsStr[i].split(":");
	   						String productId = "";
	   						String productSkuId = "";
	   						if( null != temp ){
	   							productId = temp[0];//商品ID
	   							productSkuId = temp[1];
	   						}
    						
    						Product product = productService.get(productId);
    						//product.setProductPrice(getProductPriceString(user.getId(),));
    						product = filterPriceByUser(user, product);
    						ProductSku productSku = productSkuService.get(productSkuId);
    						productSku = filterSkuPriceByUser(user, productSku);
    						//productSku = filterSkuPriceByUser(user,productSku);
    						
    						if( null != product ){
    							ProductOrderVo vo = new ProductOrderVo();
    							String haveHongbao = isHaveHongbao(user.getId(), product.getId());
    							//判断红包是否在有效期内
    							String hongbao = getHongbaoOrder(product);
    							
    							vo.setTotalCount(temp[2]);
    							vo.setName(product.getName());
    							vo.setMainImageUrl(product.getMainImageUrl());
    							vo.setTotalFeedback(product.getTotalFeedback());
    							if( StringHelper.isNotBlank(product.getPercentFeedback()) ){
    								double parseDouble = Double.parseDouble(product.getPercentFeedback());
    								int value = (int)parseDouble;
    								product.setPercentFeedback(value+"");
    							}
    							vo.setPercentFeedback(product.getPercentFeedback()==""?"100":product.getPercentFeedback());
    							//vo.setProductPrice(productSku.getProductPrice());
    							
    							vo.setProductOrginPrice(productSku.getProductOrginPrice());
    							//vo.setProductHongbao(productSku.getProductHongbao());
    							vo.setIsServenBack(product.getIsServenBack());
    							vo.setIsFreePost(product.getIsFreePost());
    							
    							if( "1".equals(haveHongbao) && NumberStringHelper.isGreaterNoEqual(hongbao, "0") ){
    								vo.setProductPrice(productSku.getProductPrice());
    								
        							String totalHongbaoTemp = NumberStringHelper.mulString(temp[2], productSku.getProductHongbao());
        							totalHongbao = NumberStringHelper.addString(totalHongbao, totalHongbaoTemp);
        							
        							String totalPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductPrice());
        							totalPrice = NumberStringHelper.addString(totalPrice, totalPriceTemp);
        							
        							String totalOriginPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
        							totalOriginPrice = NumberStringHelper.addString(totalOriginPrice, totalOriginPriceTemp);
        							
        							productsDetail.add(vo);
        							
    							}else{
    								vo.setProductPrice(productSku.getProductOrginPrice());
        							//String totalHongbaoTemp = NumberStringHelper.mulString(temp[2], productSku.getProductHongbao());
        							//totalHongbao = NumberStringHelper.addString(totalHongbao, totalHongbaoTemp);
        							
        							String totalPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
        							totalPrice = NumberStringHelper.addString(totalPrice, totalPriceTemp);
        							
        							String totalOriginPriceTemp = NumberStringHelper.mulString(temp[2], productSku.getProductOrginPrice());
        							totalOriginPrice = NumberStringHelper.addString(totalOriginPrice, totalOriginPriceTemp);
        							
        							productsDetail.add(vo);
    							}
    							
    						}
	   					}
	   					
	   					Map<String, Object> dataMap = new HashMap<String,Object>(); 
	   					
		   			    dataMap.put("products", productsDetail);
		   			    dataMap.put("mainAddress", mainAddress);
		   			    dataMap.put("paramProducts", products);
		   			    dataMap.put("paramMarketUserProductId", marketUserProductId);
		   			    dataMap.put("isHaveAddress", isHaveAddress);
		   			    
		   			    dataMap.put("totalHongbao", totalHongbao);
		   			    dataMap.put("totalOriginPrice", totalOriginPrice);
		   			    dataMap.put("totalPostFee", totalPostFee);
		   			    if( "new".equals(type) && isOneOrder(user.getId())  ){
		   			        dataMap.put("totalPrice", "1");
		   			    }else{
		   			    	dataMap.put("totalPrice", totalPrice);
		   			    }
		   			    resultMap.put(DATA, dataMap);
		   			    
		   			    result = SUCCESS;
		   			    errorCode = SUCCESS_ERROR_CODE;
		   			 	errorMsg = SUCCESS_ERROR_MSG; 
	   				}else{
    					result = FAIL;
            			errorCode = PRODUCT_EMPTY_ERROR_CODE;
                    	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
    				}
	   			    
	   			}else{
					result = LOGIN;
	    			errorCode = LOGIN_ERROR_CODE;
	            	errorMsg = LOGIN_ERROR_MSG;  	
				}
			}
	   		
		}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "preCreate", e.toString(),"预产生订单",e);
    		
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
   }
    
    
    /**
     * 用户生成订单接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/create")
    @ResponseBody
    public Map<String,Object> create( HttpServletRequest request,HttpServletResponse response,String token, String note,String addressId, String products,String marketUserProductId, String type){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) && StringHelper.isNotBlank(addressId) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				Map<String, Object> dataMap = new HashMap<String,Object>();
    				//解析 产品ID 和数量
    				String[] productsStr = products.split(",");
    				if( productsStr.length > 0 ){
    				    
    					List<OrderProducts> orderProducts = new ArrayList<OrderProducts>();
    					Date date = new Date();
    					//过期时间30分钟
    					Date dateAfter30 = CalendarHelper.getMinuteAfter(date, 30);
    					String date30 = DateHelper.formatDateTime(dateAfter30);
    					String orderId = IdGen.uuid();
    					String userId = user.getId();
    					String totalProduct = "0";
    					String totalMoney = "0";
    					//String isHaveMarket = "0";//订单是否有商家ID
    					String marketUserId = "";
    					String orderNum = RandomOrderNumHelper.getOrderNumber();
    					if( StringHelper.isNotBlank(marketUserProductId) ){
    						
    						MarketUserProduct userProduct = marketUserProductService.get(marketUserProductId);
    						if( null != userProduct ){
    							MarketUser user2 = marketUserService.get(userProduct.getUserId());
    							if( null != user2 ){
    								marketUserId = user2.getId();
    							}
    						}
    						//isHaveMarket = "1";
    					}
    					
    					for( int i=0; i<productsStr.length; i++ ){
    						String[] temp = productsStr[i].split(":");
    						if( temp.length > 2 ){
    							
    							String productId = temp[0];//商品ID
        						String productSkuId = temp[1];//商品的SKUID
        						String productCount = temp[2];//商品数量
        						
        						//Product product = productService.get(productId);
        						ProductSku productSku = productSkuService.get(productSkuId);
        						
        						/*if( StringHelper.isNotBlank(type) ){
        							productSku.setProductPrice(product.getSeckillPrice());
        						}else{
        							
        						}*/
        						productSku = filterSkuPriceByUser(user, productSku);
        						
        						String tempTotalMoney = NumberStringHelper.mulString(productSku.getProductPrice(), productCount);
        						//String tempTotalProduct = NumberStringHelper.addString(productCount, totalProduct);
        						totalMoney = NumberStringHelper.addString(tempTotalMoney, totalMoney);
        						totalProduct = NumberStringHelper.addString(productCount, totalProduct);
        						
        						OrderProducts orderProduct = new OrderProducts();
        						//6个必填项
        						orderProduct.setId(IdGen.uuid());
        						orderProduct.setIsEffective(DBConst.TRUE);
        						orderProduct.setOrgCode(ORG_CODE);
        						orderProduct.setCreateUser(CREATE_USER);
        						orderProduct.setCreateTime(date);
        						orderProduct.setUpdateTime(date);
        						//关联字段
        						orderProduct.setOrderId(orderId);
        						orderProduct.setProductId(productId);
        						orderProduct.setPropertySkuId(productSkuId);
        						orderProduct.setMarketUserProductId(marketUserProductId);//商品推广ID
        						orderProduct.setMarketUserId(marketUserId);
        						orderProduct.setUserId(userId);//用户字段
        						orderProduct.setStatus("0");//订单状态为未支付状态
        						orderProduct.setBackStatus("0");//退换货状态不生效
        						//填充字段
        						orderProduct.setIsFeedback("0");//未评价状态
        						//业务字段 
        						orderProduct.setTotalCount(productCount);//商品数量
        						
        						if( isOneOrder(user.getId()) && "new".equals(type) ){
        							orderProduct.setTotalMoney("1");//商品总金额
        		   			    }else{
        		   			    	orderProduct.setTotalMoney(tempTotalMoney);//商品总金额
        		   			    }
        						orderProducts.add(orderProduct);
    						}
    					}
    					
    					Order order = new Order();
    					//6个必填字段
    					order.setId(orderId);
    					order.setIsEffective(DBConst.TRUE);
    					order.setOrgCode(ORG_CODE);
    					order.setCreateUser(CREATE_USER);
    					order.setCreateTime(date);
    					order.setUpdateTime(date);
    					
    					//关联字段
    					order.setUserId(userId);
    					order.setUserAddressId(addressId);
    					//默认填充字段
    					order.setStatus("0");//订单状态
    					//order.setIsHaveMarket(isHaveMarket);
    					//order.setOrderIsConfirm("0");//订单未确认收货
    					order.setOrderIsExpired("0");//订单未过期
    					//order.setOrderIsFeedback("0");//订单未评价
    					//order.setOrderIsPay("0");//订单未支付 
    					//业务字段
    					order.setOrderNum(orderNum);//订单号码
    					if( isOneOrder(user.getId()) && "new".equals(type) ){
    						order.setTotalMoney("1");
		   			    }else{
		   			    	order.setTotalMoney(totalMoney);
		   			    }
    					order.setTotalProduct(totalProduct);
    					order.setOrderExpiredTime(date30);
    					order.setNote(note);
    					
    					//更新数据库
    					result = orderService.createOrder(order,orderProducts);
    					//清空购物车
    					
    					
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG; 
                    	
                    	dataMap.put(ORDER_ID, orderId);
                    	if( isOneOrder(user.getId()) && "new".equals(type) ){
                    		dataMap.put(TOTAL_MONEY, "1");
		   			    }else{
		   			    	dataMap.put(TOTAL_MONEY, totalMoney);
		   			    }
                    	
                    	resultMap.put(DATA, dataMap);
    					
    				}else{
    					result = FAIL;
            			errorCode = PRODUCT_EMPTY_ERROR_CODE;
                    	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
    				}
    				
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallOrderInterface", "create", e.toString(),"生成订单",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * 用户生成订单接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/createSeckill")
    @ResponseBody
    public Map<String,Object> createSeckill( HttpServletRequest request,HttpServletResponse response,String token, String note,String addressId, String products,String marketUserProductId){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(products) && StringHelper.isNotBlank(addressId) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				Map<String, Object> dataMap = new HashMap<String,Object>();
    				//解析 产品ID 和数量
    				String[] productsStr = products.split(",");
    				if( productsStr.length > 0 ){
    				    
    					List<OrderProducts> orderProducts = new ArrayList<OrderProducts>();
    					Date date = new Date();
    					//过期时间30分钟
    					Date dateAfter30 = CalendarHelper.getMinuteAfter(date, 30);
    					String date30 = DateHelper.formatDateTime(dateAfter30);
    					String orderId = IdGen.uuid();
    					String userId = user.getId();
    					String totalProduct = "0";
    					String totalMoney = "0";
    					//String isHaveMarket = "0";//订单是否有商家ID
    					String marketUserId = "";
    					String orderNum = RandomOrderNumHelper.getOrderNumber();
    					if( StringHelper.isNotBlank(marketUserProductId) ){
    						
    						MarketUserProduct userProduct = marketUserProductService.get(marketUserProductId);
    						if( null != userProduct ){
    							MarketUser user2 = marketUserService.get(userProduct.getUserId());
    							if( null != user2 ){
    								marketUserId = user2.getId();
    							}
    						}
    						//isHaveMarket = "1";
    					}
    					
    					for( int i=0; i<productsStr.length; i++ ){
    						String[] temp = productsStr[i].split(":");
    						if( temp.length > 2 ){
    							
    							String productId = temp[0];//商品ID
    							
        						String productSkuId = temp[1];//商品的SKUID
        						String productCount = temp[2];//商品数量
        						ProductSku productSku = productSkuService.get(productSkuId);
        						
        						Product product = productService.get(productId);
        						productSku.setProductPrice(product.getSeckillPrice());
        						
        						//productSku = filterSkuPriceByUser(user, productSku);
        						
        						
        						String tempTotalMoney = NumberStringHelper.mulString(productSku.getProductPrice(), productCount);
        						//String tempTotalProduct = NumberStringHelper.addString(productCount, totalProduct);
        						totalMoney = NumberStringHelper.addString(tempTotalMoney, totalMoney);
        						totalProduct = NumberStringHelper.addString(productCount, totalProduct);
        						
        						OrderProducts orderProduct = new OrderProducts();
        						//6个必填项
        						orderProduct.setId(IdGen.uuid());
        						orderProduct.setIsEffective(DBConst.TRUE);
        						orderProduct.setOrgCode(ORG_CODE);
        						orderProduct.setCreateUser(CREATE_USER);
        						orderProduct.setCreateTime(date);
        						orderProduct.setUpdateTime(date);
        						//关联字段
        						orderProduct.setOrderId(orderId);
        						orderProduct.setProductId(productId);
        						orderProduct.setPropertySkuId(productSkuId);
        						orderProduct.setMarketUserProductId(marketUserProductId);//商品推广ID
        						orderProduct.setMarketUserId(marketUserId);
        						orderProduct.setUserId(userId);//用户字段
        						orderProduct.setStatus("0");//订单状态为未支付状态
        						orderProduct.setBackStatus("0");//退换货状态不生效
        						//填充字段
        						orderProduct.setIsFeedback("0");//未评价状态
        						//业务字段 
        						orderProduct.setTotalCount(productCount);//商品数量
        						orderProduct.setTotalMoney(tempTotalMoney);//商品总金额
        						
        						orderProducts.add(orderProduct);
    						}
    					}
    					
    					Order order = new Order();
    					//6个必填字段
    					order.setId(orderId);
    					order.setIsEffective(DBConst.TRUE);
    					order.setOrgCode(ORG_CODE);
    					order.setCreateUser(CREATE_USER);
    					order.setCreateTime(date);
    					order.setUpdateTime(date);
    					
    					//关联字段
    					order.setUserId(userId);
    					order.setUserAddressId(addressId);
    					//默认填充字段
    					order.setStatus("0");//订单状态
    					//order.setIsHaveMarket(isHaveMarket);
    					//order.setOrderIsConfirm("0");//订单未确认收货
    					order.setOrderIsExpired("0");//订单未过期
    					//order.setOrderIsFeedback("0");//订单未评价
    					//order.setOrderIsPay("0");//订单未支付 
    					//业务字段
    					order.setOrderNum(orderNum);//订单号码
    					order.setTotalMoney(totalMoney);
    					order.setTotalProduct(totalProduct);
    					order.setOrderExpiredTime(date30);
    					order.setNote(note);
    					
    					//更新数据库
    					result = orderService.createOrder(order,orderProducts);
    					//清空购物车
    					
    					
            			errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG; 
                    	
                    	dataMap.put(ORDER_ID, orderId);
                    	dataMap.put(TOTAL_MONEY, totalMoney);
                    	resultMap.put(DATA, dataMap);
    					
    				}else{
    					result = FAIL;
            			errorCode = PRODUCT_EMPTY_ERROR_CODE;
                    	errorMsg = PRODUCT_EMPTY_ERROR_MSG; 
    				}
    				
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallOrderInterface", "create", e.toString(),"生成订单",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    /**
     * 展示用户的所有订单信息
     
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String,Object> list( HttpServletRequest request,HttpServletResponse response, String token, String orderType){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderType) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				OrderExample example = new OrderExample();
    				example = this.handlePageQuery(request, example);
    				example.setOrderByClause("CREATE_TIME DESC");
    				Criteria criteria = example.createCriteria();
    				criteria.andIsEffectiveEqualTo(DBConst.TRUE);//过滤是否删除标记
    				criteria.andUserIdEqualTo(user.getId());//过滤当前用户
    				
    				if(NO_PAY.equals(orderType)){
    					//待支付
    					criteria.andOrderIsPayEqualTo(DBConst.FALSE);
    				}
    				
    				if(NO_FEEDBACK.equals(orderType)){
    					//待评价
    					criteria.andOrderIsFeedbackEqualTo(DBConst.FALSE);
    				}
    				
    				if(NO_COMFIRM.equals(orderType)){
    					//待收货
    					criteria.andOrderIsConfirmEqualTo(DBConst.FALSE);
    				}
    				
    				if(COMEBACK.equals(orderType)){
    					//退换货
    					criteria.andOrderIsComebackEqualTo(DBConst.TRUE);
    				}
    				List<Order> list = orderService.list(example);
    				
    				resultMap.put(DATA, list);
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  
    			}
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	log(e);
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    */
    
    
    /**
     * 展示用户的所有订单信息
     */
    @RequestMapping(value="/list")
    @ResponseBody
    public Map<String,Object> list( HttpServletRequest request,HttpServletResponse response, String token, String orderType , Integer start, Integer length ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderType) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				Map<String, Object> dataMap = new HashMap<String,Object>();
    				
    				List<OrderProductsFeedbackVo> list = null;
    				Integer totalCount = 0;
    				OrderProductsParam param = new OrderProductsParam(); 
    				if(NO_PAY.equals(orderType)){
    					//待支付
    					orderType = "0";
    					OrderExample example = new OrderExample();
    					example.setOrderByClause("CREATE_TIME DESC");
    					example = this.handlePageQuery(request, example);
    					Criteria criteria = example.createCriteria();
    					criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    					criteria.andUserIdEqualTo(user.getId());
    					criteria.andStatusEqualTo("0");
    					totalCount = orderService.count(example);
    					List<Order> orders = orderService.list(example);
    					List<OrderVo> vos = new ArrayList<OrderVo>();
    					if( orders.size() > 0 ){
    						
    						for( Order tmp : orders ){
    							OrderVo orderVo = new OrderVo();
    							orderVo.setId(tmp.getId());
    							orderVo.setOrderNum(tmp.getOrderNum());
    							orderVo.setOrderExpiredTime(tmp.getOrderExpiredTime());
    							orderVo.setOrderIsPay(tmp.getOrderIsPay());
    							orderVo.setTotalMoney(tmp.getTotalMoney());
    							orderVo.setTotalProduct(tmp.getTotalProduct());
    							
    							OrderProductsExample example2 = new OrderProductsExample();
    							com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria criteria2 = example2.createCriteria();
    							criteria2.andOrderIdEqualTo(tmp.getId());
    							List<OrderProducts> list2 = orderProductsService.list(example2);
    							List<OrderProductsVo> productsVo = new ArrayList<OrderProductsVo>();
    							for( OrderProducts ttmp: list2 ){
    								Product product = productService.get(ttmp.getProductId());
    								OrderProductsVo vo = new OrderProductsVo();
    								vo.setMainImageUrl(product.getMainImageUrl());
    								vo.setName(product.getName());
    								vo.setIsServenBack(product.getIsServenBack());
    								vo.setIsFreePost(product.getIsFreePost());
    								vo.setProductPrice(product.getProductPrice());
    								vo.setProductHongbao(product.getProductHongbao());
    								vo.setProductOrginPrice(product.getProductOrginPrice());
    								vo.setTotalFeedback(product.getTotalFeedback());
    								vo.setPrecentFeedback(product.getPercentFeedback()==""?"100":product.getPercentFeedback());
    								vo.setTotalCount(ttmp.getTotalCount());
    								vo.setProductId(ttmp.getProductId());
    								productsVo.add(vo);
    							}
    							orderVo.setProducts(productsVo);
    							vos.add(orderVo);
    						}
    					}
    					dataMap.put("products", vos);
    				}
    				

    				if(NO_FAHUO.equals(orderType)){
    					//待收货
    					orderType = "1";
    					param.setStatus(orderType);
    					param.setUserId(user.getId());
    					param.setStart(start);
    					param.setLength(length);
    					totalCount = orderProductsService.countListOrderProducts(param);
    					list = orderProductsService.listOrderProducts(param);
    					dataMap.put("products", list);
    					
    				}
    				
    				
    				if(NO_COMFIRM.equals(orderType)){
    					//待收货
    					orderType = "2";
    					param.setStatus(orderType);
    					param.setUserId(user.getId());
    					param.setStart(start);
    					param.setLength(length);
    					totalCount = orderProductsService.countListOrderProducts(param);
    					list = orderProductsService.listOrderProducts(param);
    					dataMap.put("products", list);
    					
    				}
    				
    				if(COMEBACK.equals(orderType)){
    					//退换货
    					orderType = "4";
    					param.setStatus(orderType);
    					param.setUserId(user.getId());
    					param.setStart(start);
    					param.setLength(length);
    					totalCount = orderProductsService.countListOrderProducts(param);
    					list = orderProductsService.listOrderProducts(param);
    					dataMap.put("products", list);
    				}
    				
    				if(NO_FEEDBACK.equals(orderType)){
    					//待评价
    					orderType = "3";
    					param.setStatus(orderType);
    					param.setUserId(user.getId());
    					param.setStart(start);
    					param.setLength(length);
    					totalCount = orderProductsService.countListNoFeedback(param);
    					list = orderProductsService.listNoFeedback(param);
    					dataMap.put("products", list);
    				}
    				
    				if(SUCCESS.equals(orderType)){
    					//待评价
    					orderType = "3";
    					param.setStatus(orderType);
    					param.setUserId(user.getId());
    					param.setStart(start);
    					param.setLength(length);
    					totalCount = orderProductsService.countListNoFeedback(param);
    					list = orderProductsService.listNoFeedback(param);
    					dataMap.put("products", list);
    				}
    				
    				dataMap.put("totalCount", totalCount);
    				resultMap.put(DATA, dataMap);
    				result = SUCCESS;
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  
    			}
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "list", e.toString(),"待付款，待收货，待评价，退换货接口",e);
    		
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
    /**
     * 展示订单信息下的产品信息
     */
    @RequestMapping(value="/listProducts")
    @ResponseBody
    public Map<String,Object> listProducts( HttpServletRequest request,HttpServletResponse response, String orderId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(orderId) ){
    			OrderProductsExample example = new OrderProductsExample();
    			com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample.Criteria criteria = example.createCriteria();
    			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    			criteria.andOrderIdEqualTo(orderId);
    			
    			List<OrderProducts> list = orderProductsService.list(example);
    			resultMap.put(DATA, list);
    			
    			result = SUCCESS;
    			errorCode = SUCCESS_ERROR_CODE;
            	errorMsg = SUCCESS_ERROR_MSG;  
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "listProducts", e.toString(),"根据订单查找产品",e);
    		
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
    /**
     * APP商品详情信息
     * @param categoryId 类别ID
     * @param orderType 排序类型
     * @param minMaxPrice 最小到最大的价格区间，中间用-号相隔
     * @param minMaxPrice 最小到最大的销量区间     中间用-号相隔
     * @return
     */
    @RequestMapping(method= RequestMethod.POST,value="/feedback")
    @ResponseBody
    public Map<String,Object> feedback(HttpServletRequest request,HttpServletResponse response,String token,String orderProductsId,String content,String starDegree,String imageUrls){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
     	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) && StringHelper.isNotBlank(starDegree)){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				OrderProducts orderProducts = orderProductsService.get(orderProductsId);
    				String productId = orderProducts.getProductId();//获得商品ID
    				
    				String skuId = orderProducts.getPropertySkuId();
    				ProductSku productSku = productSkuService.get(skuId);
    				String propertys = productSku.getProductPropertys();
    				
    				//将当前的商品修改为已评论
    				orderProducts.setIsFeedback("1");
    				
    				Order order = null;
    				
    				//更新商品的评论比与评论图片统计数量
    				Product product = productService.get(productId);
    				//判断有没有图片评论
    				if(StringHelper.isNotBlank(imageUrls)){
    					String totalFeedbackImage = "0";
    					if(StringHelper.isNotBlank(product.getTotalFeedbackImage())){
    						totalFeedbackImage = product.getTotalFeedbackImage();
    					}
    					totalFeedbackImage = NumberStringHelper.addString(totalFeedbackImage, "1");
    					product.setTotalFeedbackImage(totalFeedbackImage);
    				}
    				//总评论数
    				String totalFeedback = "0";
    				if( StringHelper.isNotBlank(product.getTotalFeedback()) ){
    					totalFeedback = product.getTotalFeedback();
    				}
    				totalFeedback = NumberStringHelper.addString(totalFeedback,"1");
    				product.setTotalFeedback(totalFeedback);
    				//统计好评论数量
    				if(StringHelper.isNotBlank(starDegree)){
    					//获得好评率的设置
    					String set = sysSettingService.getByKey("GOOD_FEEDBACK_DEGREE");
    					if( NumberStringHelper.isGreater(starDegree, set) ){
    					    //好评加1
    						String goodFeedback = "0";
    						if(StringHelper.isNotBlank(product.getTotalFeedbackGood())){
    							goodFeedback=product.getTotalFeedbackGood();
    						}
    						goodFeedback = NumberStringHelper.addString(goodFeedback, "1");
    						product.setTotalFeedbackGood(goodFeedback);
    					}
    				}
    				
    				//重新算算好评率
    				String percent = NumberStringHelper.divString(product.getTotalFeedbackGood(), totalFeedback,2);
    				percent = NumberStringHelper.mulString(percent, "100");
    				product.setPercentFeedback(percent);
    				
    				//添加商品評論信息
    				ProductFeedback feedback = new ProductFeedback();
    				//添加6個必填字段
    				feedback.setId(IdGen.uuid());
    				feedback.setIsEffective(DBConst.TRUE);
    			    feedback.setOrgCode(ORG_CODE);
    			    feedback.setCreateUser(CREATE_USER);
    			    feedback.setCreateTime(new Date());
    			    feedback.setUpdateTime(new Date());
    			    
    				feedback.setUserId(user.getId());
    				feedback.setProductId(productId);
    				feedback.setContent(content);
    				feedback.setStarDegree(starDegree);
    				feedback.setImageUrls(imageUrls);
    				feedback.setNote(propertys);
    				resultMap.put(DATA, "success");
    				result = productFeedbackService.addAndUpdateProduct(order,orderProducts,feedback,product);
        			errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  	
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
    		
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallOrderInterface", "feedbacks", e.toString(),"根据商品查找所有的评价信息",e);
    		
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    /**
     * 用户商品确认收货b530fe2e03754a77beca1ddd722dc1f8
     */
    @RequestMapping(value="/del")
    @ResponseBody
    public Map<String,Object> del( HttpServletRequest request,HttpServletResponse response,String token, String orderId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(orderId) ){
    			Order order = orderService.get(orderId);
    			if( null != order && "0".equals(order.getStatus()) ){
    				result = orderService.delete(order);
    				errorCode = SUCCESS_ERROR_CODE;
    		    	errorMsg = SUCCESS_ERROR_MSG;
    			}
    		}
    	}catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "del", e.toString(),"用户取消订单",e);
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
    
    public boolean orderIsAllConfirm( String orderId, String orderProductsId ){
    	OrderProductsExample example = new OrderProductsExample();
    	//如果订单项中除了刚才确认收货的订单，说明全部已经收货了
    	example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderIdEqualTo(orderId).andIdNotEqualTo(orderProductsId).andStatusEqualTo("2");
    	List<OrderProducts> list = orderProductsService.list(example);
    	if( list.size() > 0 ){
    		return false;
    	}else{
    		return true;
    	}
    }
    
    /**
     * 用户商品确认收货
     */
    @RequestMapping(value="/confirm")
    @ResponseBody
    public Map<String,Object> confirm( HttpServletRequest request,HttpServletResponse response,String token, String orderProductsId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				//判断订单号码是否为支付状态
    				OrderProducts orderProducts = orderProductsService.get(orderProductsId);
    				if( null != orderProducts && "2".equals(orderProducts.getStatus()) ){
    					Order order = orderService.get(orderProducts.getOrderId());//可为null
        				Product product = productService.get(orderProducts.getProductId());
        				PreMoney preMoney = null;//可为null
        				PayMoney payMoney = null;//可为null
        				
        				
        				//List<ExpendLog> expendLogs = new ArrayList<ExpendLog>();//可为null
        				//List<Statis> statiss = new ArrayList<Statis>();//可为null
        				List<MarketUser> marketUsers = new ArrayList<MarketUser>();//可为null
        				//List<MarketProfit> marketProfits = new ArrayList<MarketProfit>();
        				List<ProfitMoney> profitMoneys = new ArrayList<ProfitMoney>();
        				
        				//设置订单项为确认支付状态
        				orderProducts.setIsConfirm("1");//已确认收货状态 
        				orderProducts.setStatus("3");//交易成功
        				//判断其它的订单项是否也交易成功
        				if( orderIsAllConfirm( order.getId(), orderProducts.getId() ) ){
        					order.setStatus("3");
        				}
        				//商品销量加1
        				String totalSales = "0";
        				if( StringHelper.isNotBlank(totalSales) ){
        					totalSales = product.getTotalSales();
        				}
        				totalSales = NumberStringHelper.addString(totalSales, "1");
        				product.setTotalSales(totalSales);
        				
        				MarketUserProduct marketUserProduct = null;
        				
        				//如果有商家 ID ，则找到相应的 预计收益信息  更新为支付状态   统计商家推广商品赚了多少钱  商家添加收益
        				//MarketUser marketUser = getMarketUserByMallUser(user);

						//查找预计收益信息
    					preMoney = preMoneyService.getByOrderProductsId(orderProductsId);
    					
    					
    					
    					if( null != preMoney ){
    						preMoney.setIsGive("1");
    						MarketUser marketUser = marketUserService.get(preMoney.getMarketUserId());
    						//添加收益记录
        					ProfitMoney profit = getProfitMoney( orderProducts,marketUser,preMoney.getPreMoney(),"VIP用户“"+user.getUserNickName()+"”确认收货《"+product.getName()+"》获得佣金"+preMoney.getPreMoney()+"元","001");
        					profitMoneys.add(profit);
        					
        					//添加云店用户商品赚了多少钱
        					marketUserProduct = resetMarketUserProductProfit(orderProducts.getMarketUserProductId(),preMoney.getPreMoney());
        					
        					//添加云店上店用户佣金
        					//MarketUser marketUserOne = marketUserService.get(orderProducts.getMarketUserId());
        					
        					marketUsers.add(resetMarketUserProfit(marketUser,preMoney.getPreMoney(),orderProducts.getTotalCount()));
    	    				
        					
        					//添加三级分销的功能提成
    	    				String one = sysSettingService.getByKey("MARKET_SET_ONE_PEOPLE");
    	    				String two = sysSettingService.getByKey("MARKET_SET_TWO_PEOPLE");
    	    				String onePercent = sysSettingService.getByKey("MARKET_SET_ONE_PERCENT");
    	    				String twoPercent = sysSettingService.getByKey("MARKET_SET_TWO_PERCENT");
    	    				//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
    	    				MarketUser invitingUser = marketUserService.get(marketUser.getInvitingId());
    	    				String successPeople = "0";
    	    				if( null != invitingUser && StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
    	    					successPeople = invitingUser.getSuccessPeople();
    	    				}
    	    				if( null != invitingUser ){
    	    					
    	    					if( NumberStringHelper.isGreater(successPeople, one ) ){
    	    						String moneyOne = getPercentMoney(preMoney.getPreMoney(), onePercent );
        	    					//添加收益记录
        	    					ProfitMoney profitOne = getProfitMoney( orderProducts,invitingUser,moneyOne,"VIP用户“"+user.getUserNickName()+"”确认收货《"+product.getName()+"》,获得一级店主“"+marketUser.getUserNickName()+"”的佣金提成"+moneyOne+"元","002");
        	    					profitMoneys.add(profitOne);
        	    					//添加云店用户
        		    			    marketUsers.add(resetMarketUserProfit(invitingUser,moneyOne));
    	    					}
    		    			    
    		    			    //查找商家的上上级信息
    		    				MarketUser topInvitingUser = marketUserService.get(invitingUser.getInvitingId());
    		    				if( null != topInvitingUser ){
    		    					String successPeopleTwo = "0";
    			    				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
    			    					successPeopleTwo = topInvitingUser.getSuccessPeople();
    			    				}
    			    				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
    			    					String moneyTwo = getPercentMoney(preMoney.getPreMoney(), twoPercent );
    			    					//添加收益记录
    			    					ProfitMoney profitTwo = getProfitMoney( orderProducts,topInvitingUser,moneyTwo,"VIP用户“"+user.getUserNickName()+"”确认收货《"+product.getName()+"》获得二级店主“"+invitingUser.getUserNickName()+"”的佣金提成"+moneyTwo+"元","002");
    			    					profitMoneys.add(profitTwo);
    			    					//添加云店用户
    				    			    marketUsers.add(resetMarketUserProfitTop(topInvitingUser,moneyTwo));
    			    				}
    		    				}
    		    				
    	    				}
    					}
    					 
        				result = orderService.confirmV2(orderProducts,product,order,preMoney,payMoney,marketUsers,marketUserProduct,profitMoneys);
        				
        				errorCode = SUCCESS_ERROR_CODE;
                    	errorMsg = SUCCESS_ERROR_MSG;  	
    				}else{
    					result = FAIL;
            			errorCode = ORDER_NULL_ERROR_CODE;
                    	errorMsg = ORDER_NULL_ERROR_MSG; 
    				}
    			}else{ 
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "confirm", e.toString(),"用户确认收货",e);
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
    /**
     * 
     * @param order 订单
     * @param user VIP购买用户
     * @param money 云店用户
     * @param note 备注信息
     * @param type 类型
     * @return
     */
    public ProfitMoney getProfitMoney( OrderProducts orderProducts ,MarketUser user, String money, String note ,String type ){
    	
    	String orderId = orderProducts.getOrderId();
    	Order order = orderService.get(orderId);
    	
    	ProfitMoney profitMoney = new ProfitMoney();
    	profitMoney.setId(IdGen.uuid());
    	profitMoney.setIsEffective(DBConst.TRUE);
    	profitMoney.setCreateTime(new Date());
    	profitMoney.setUpdateTime(new Date());
    	profitMoney.setCreateUser(CREATE_USER);
    	profitMoney.setOrgCode(ORG_CODE);
    	
    	profitMoney.setUserId(order.getUserId());
    	profitMoney.setMarketUserId(user.getId());
        profitMoney.setType(type);
        profitMoney.setNote(note);
        profitMoney.setMoney(money);
        profitMoney.setUserNickName(user.getUserNickName());
    	
    	profitMoney.setOrderId(order.getId());
    	profitMoney.setOrderNum(order.getOrderNum());
    	profitMoney.setOrderPayTime(DateHelper.getDateByStringDate(order.getPayTime()));
    	profitMoney.setOrderTotalMoney(orderProducts.getTotalMoney());
		
    	return profitMoney;
    }
    
    /**
     * 添加云店商品共赚了多少钱
     * @param marketUserProductId
     * @param money
     * @return
     */
    public MarketUserProduct resetMarketUserProductProfit( String marketUserProductId, String money ){
    	//设置云店主的商品共赚了多少钱
	    MarketUserProduct marketUserProduct = marketUserProductService.get(marketUserProductId);
	    if( null != marketUserProduct ){
	    	String marketUserProductMoney = "0";
			if( StringHelper.isNotBlank(marketUserProduct.getProfit()) ){
				marketUserProductMoney = marketUserProduct.getProfit();
			}
			marketUserProductMoney = NumberStringHelper.addString(marketUserProductMoney, money );
			marketUserProduct.setProfit(marketUserProductMoney);
	    }
		return marketUserProduct;
    }
    
    /**
     * 添加云店收益
     * @param user
     * @return
     */
    public MarketUser resetMarketUserProfit( MarketUser user, String money ){
		//添加商家账户收益
		String marketUserMoney = "0";
		if( StringHelper.isNotBlank(user.getMoney()) ){
			marketUserMoney = user.getMoney();
		}
		marketUserMoney = NumberStringHelper.addString(marketUserMoney, money);
		user.setMoney(marketUserMoney);
		
		//预计收益相减
		String marketUserPreMoney = "0";
		if( StringHelper.isNotBlank(user.getPreProfit()) ){
			marketUserPreMoney = user.getPreProfit();
		}
		marketUserPreMoney = NumberStringHelper.subtractString( marketUserPreMoney, money );
		user.setPreProfit(marketUserPreMoney);
		
		//统计总收益信息
		String marketUserTotalMoney = "0";
		if( StringHelper.isNotBlank(user.getTotalProfit()) ){
			marketUserTotalMoney = user.getTotalProfit();
		}
		marketUserTotalMoney = NumberStringHelper.addString( marketUserTotalMoney, money );
		user.setTotalProfit(marketUserTotalMoney);
		
		return user;
    } 
    
    /**
     * 添加云店收益
     * @param user
     * @return
     */
    public MarketUser resetMarketUserProfitTop( MarketUser user, String money ){
		//添加商家账户收益
		String marketUserMoney = "0";
		if( StringHelper.isNotBlank(user.getMoney()) ){
			marketUserMoney = user.getMoney();
		}
		marketUserMoney = NumberStringHelper.addString(marketUserMoney, money);
		user.setMoney(marketUserMoney);
		
		
		//统计总收益信息
		String marketUserTotalMoney = "0";
		if( StringHelper.isNotBlank(user.getTotalProfit()) ){
			marketUserTotalMoney = user.getTotalProfit();
		}
		marketUserTotalMoney = NumberStringHelper.addString( marketUserTotalMoney, money );
		user.setTotalProfit(marketUserTotalMoney);
		
		return user;
    } 
    
    /**
     * 添加云店收益
     * @param user
     * @return
     */
    public MarketUser resetMarketUserProfit( MarketUser user, String money, String totalProduct ){
		//添加商家账户收益
		String marketUserMoney = "0";
		if( StringHelper.isNotBlank(user.getMoney()) ){
			marketUserMoney = user.getMoney();
		}
		marketUserMoney = NumberStringHelper.addString(marketUserMoney, money);
		user.setMoney(marketUserMoney);
		
		//预计收益相减
		String marketUserPreMoney = "0";
		if( StringHelper.isNotBlank(user.getPreProfit()) ){
			marketUserPreMoney = user.getPreProfit();
		}
		marketUserPreMoney = NumberStringHelper.subtractString( marketUserPreMoney, money );
		user.setPreProfit(marketUserPreMoney);
		
		//统计总收益信息
		String marketUserTotalMoney = "0";
		if( StringHelper.isNotBlank(user.getTotalProfit()) ){
			marketUserTotalMoney = user.getTotalProfit();
		}
		marketUserTotalMoney = NumberStringHelper.addString( marketUserTotalMoney, money );
		user.setTotalProfit(marketUserTotalMoney);
		
		//用户商品数量添加
	    String marketUserTotalProduct = "0";
	    if( StringHelper.isNotBlank(user.getTotalProduct()) ){
	    	marketUserTotalProduct = user.getTotalProduct();
	    }
	    marketUserTotalProduct = NumberStringHelper.addString( marketUserTotalProduct, totalProduct );
		user.setTotalProduct(marketUserTotalProduct);
		
		return user;
    } 
    
    /**
     * 返回一个百分比的金额
     * @param money
     * @param percent
     * @return
     */
    public String getPercentMoney( String money, String percent ){
    	String replace = percent.replace("%", "");
    	String mulString = NumberStringHelper.mulString(money, replace);
    	String divString = NumberStringHelper.divString(mulString, "100", 2);
    	return divString;
    }
    
    /**
     * 用户商品收到货后不满意 ，退换货
     */
    @RequestMapping(value="/comeback")
    @ResponseBody
    public Map<String,Object> comeback( HttpServletRequest request,HttpServletResponse response,String token, String orderProductsId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) ){
    			MallUser user = getMallUserByToken(token);
    			if( null != user ){
    				
    				//判断订单是否在七天内，（暂时先不考虑这个限制）
    				OrderProducts orderProducts = orderProductsService.get(orderProductsId);
    				orderProducts.setStatus("4");//退换货，未发货
    				orderProducts.setBackStatus("1");//退换货状态
    				//如果不在则提示 无法退换货
    				//如果在则更新退换货标志，
    				//提示用户 添加物流信息  如果没有物流信息  则将订单改成待发货   
    				//每个订单都 会有相应的有效时间——更新订单的有效时间为设置的值
    				//用户点击待发货  可以更新待发货为已发货状态   （注意：用户申请退款后未发货的这段时间，也被算作用户的七天时间内）
    				
    				result = orderProductsService.edit(orderProducts);
    				
    				PreMoneyExample example = new PreMoneyExample();
    				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderProductsIdEqualTo(orderProductsId);
    				List<PreMoney> list = preMoneyService.list(example);
    				if( list.size()>0 ){
    					for( PreMoney temp : list ){
    						temp.setIsEffective(DBConst.FALSE);
    						preMoneyService.edit(temp);
    						MarketUser marketUser = marketUserService.get(temp.getMarketUserId());
    						String preMoney = "0";
    						if( StringHelper.isNotBlank(marketUser.getPreProfit()) ){
    							preMoney = marketUser.getPreProfit();
    						}
    						preMoney = NumberStringHelper.subtractString(preMoney, temp.getPreMoney());
    						marketUser.setPreProfit(preMoney);
    						marketUserService.edit(marketUser);
    					}
    				}
    				
    				errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  	
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "comeback", e.toString(),"用户申请退换货",e);
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
    
    /**
     * 用户商品收到货后不满意 ，退换货,填写物流信息
     */
    @RequestMapping(value="/comebackExpress")
    @ResponseBody
    public Map<String,Object> comebackExpress( HttpServletRequest request,HttpServletResponse response,String token, String orderProductsId, String expressName, String expressNum ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(token) &&  StringHelper.isNotBlank(orderProductsId) && StringHelper.isNotBlank(expressNum) ){
    			MallUser user = getMallUserByToken(token);
    			if( null!=user ){
    				OrderProducts orderProducts = orderProductsService.get(orderProductsId);
    				orderProducts.setStatus("2");//订单项设置成 退换货 已发货状态 
    				OrderExpress orderPress = new OrderExpress();
    				//六个必填字段
    				orderPress.setId(IdGen.uuid());
    				orderPress.setIsEffective(DBConst.TRUE);
    				orderPress.setCreateTime(new Date());
    				orderPress.setUpdateTime(new Date());
    				orderPress.setCreateUser(CREATE_USER);
    				orderPress.setOrgCode(ORG_CODE);
    				
    				orderPress.setIsComeback("1");
    				orderPress.setExpressName(expressName);
    				orderPress.setExpressNum(expressNum);
    				orderPress.setOrderProductsId(orderProductsId);
    				
    				//提示用户 添加物流信息  如果没有物流信息  则将订单改成待发货
    				//用户点击待发货  可以更新待发货为已发货状态 
    				//如果是商家推荐，找到商家，减少预计收益，添加收益
    				result = orderService.comebackExpress( orderProducts, orderPress );
    				//更新数据库
    				errorCode = SUCCESS_ERROR_CODE;
                	errorMsg = SUCCESS_ERROR_MSG;  	
    			}else{
    				result = LOGIN;
        			errorCode = LOGIN_ERROR_CODE;
                	errorMsg = LOGIN_ERROR_MSG;  	
    			}
    		}
	    }catch(Exception e){
			errorCode = SERVER_ERROR_CODE;
	    	errorMsg = SERVER_ERROR_MSG;
	    	//log(e);
	    	logException("MallOrderInterface", "comebackExpress", e.toString(),"用户申请退换货后填写物流信息",e);
	    	
		}
		resultMap.put(RESULT, result);
		resultMap.put(ERROR_CODE, errorCode);
		resultMap.put(ERROR_MSG, errorMsg);
		isCrrossDomain(response);
		return resultMap;
    }
    
}